package inits

import (
	"2212b/golang-websocket-chatroom/config"
	"2212b/golang-websocket-chatroom/global"
	"2212b/golang-websocket-chatroom/internal/model"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

func InitMysql() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	mysqlConf := config.AppConf.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info)})
	if err != nil {
		print("MySQL连接失败")
		return
	}
	log.Println("MySQL连接成功")
	err = global.DB.AutoMigrate(&model.User{}, &model.ChatHistory{})
	if err != nil {
		print("MySQL迁移失败")
		return
	}
	log.Println("MySQL迁移成功")

}
